package com.guoby.controller.hello;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guoby.model.User;
import com.guoby.propertice.UserProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * Created by pactera on 2018/3/8.
 */
@RestController
@CrossOrigin
public class HelloController {

    // 获取application.yml 中的值
    @Value("${guoby}")
    private String guo;

    @Autowired
    private UserProperties userProperties;

    @RequestMapping(value = {"/hello", "/hi"},method = RequestMethod.GET)
    public String hello(){
        return "hello controller " + userProperties.getUsername();
    }

    @GetMapping(value = "/say/{id}")
    public String say(@PathVariable Integer id){
        return "url参数测试：{id}=" + id;
    }

    @GetMapping("/json")
    public String strJson() throws JsonProcessingException {

        ObjectMapper objectMapper=new ObjectMapper();
        User user = new User();
        user.setUsername("历史");
        user.setAge(22);
        user.setAge(1);
        user.setPassword("lisi");

        String strJson = objectMapper.writeValueAsString(user);

        return strJson;
    }

    @GetMapping("/object")
    public String strToObject() throws IOException {
        String str = "{\"id\":321,\"username\":\"历史\",\"password\":\"lisi\",\"age\":1}";

        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(str, User.class);

        return "{id:"+user.getId()+"}";
    }

    @PostMapping("/postjson")
    public String postJson(@RequestBody User user) throws JsonProcessingException {
        System.out.println("post request");

        ObjectMapper objectMapper=new ObjectMapper();
        User user1 = new User();
        user1.setUsername(user.getUsername());
        user1.setAge(user.getAge());
        user1.setPassword(user.getPassword());

        String strJson = objectMapper.writeValueAsString(user1);
        return strJson;
    }

    @GetMapping("/getCookie")
    public String getCookie(@CookieValue("cookie1") String cookie1) throws JsonProcessingException {
        ObjectMapper objectMapper=new ObjectMapper();
        String res = objectMapper.writeValueAsString("{cookie:"+cookie1+"}");
        return res;
    }

    @GetMapping("/getHeader")
    public String getHeader(@RequestHeader("header1") String header1,
                            @RequestHeader("header2") String header2){
        ObjectMapper objectMapper=new ObjectMapper();
        String res = null;
        try {
            res = objectMapper.writeValueAsString("{header1:"+header1+",header2:"+header2+"}");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return res;
    }
}
